package com.example.mq.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

@Data
public class Exchange {
    private String name;
    private ExchangeType exchangeType;
    private boolean durable;

    //  拓展功能
    //  自动删除
    private boolean autoDelete;
    //  arguments 表示创建交换机时指定的一些额外的参数选项，通过不同的参数，实现不同的功能
    private Map<String,Object> arguments = new HashMap<>();


    public Exchange(String name, ExchangeType exchangeType, boolean durable, boolean autoDelete) {
        this.name = name;
        this.exchangeType = exchangeType;
        this.durable = durable;
        this.autoDelete = autoDelete;
    }

    //  把 map 存入数据库时，要重写 map 的 getter，setter 方法（序列化对象）
    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            //  objectMapper 可以序列空指针，序列化后的结果是 "null" 字符串
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
    public void setArguments(String argumentsJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(argumentsJson,
                    new TypeReference<HashMap<String, Object>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
    //  方便测试，再写一组getter，setter
    public Object getArguments(String key) {
        return arguments.get(key);
    }
    public void setArguments(Map<String,Object> arguments) {
        this.arguments = arguments;
    }
    public void setArguments(String key,String value) {
        arguments.put(key,value);
    }
}
